package com.uottawa.busstopreminder.dao;


import java.util.ArrayList;
import java.util.List;

import com.uottawa.busstopreminder.domain.LocationHistory;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class BaseDAO extends SQLiteOpenHelper {
	public static final int VERSION = 1;
	public static final String DB_NAME = "app_db.sqlite";
	Context context;
	

	public BaseDAO(Context context) 
	{
		super(context, DB_NAME, null, VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createTable(db);
	}

	private void createTable(SQLiteDatabase db) {
		db.execSQL("create table location_history (" +
						"time text, " +
						"location  text, " +
						"precision text" +
				")"
			);		
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}
	

	/**
	 * @param alarm
	 * @param values
	 */
	private void createContentValues(LocationHistory history, ContentValues values) {
		values.put("time", history.getTime());
		values.put("location", history.getLocation());
		values.put("precision", history.getPrecision() );
	}
	
	public long saveLocation(LocationHistory history)
	{
		ContentValues values = new ContentValues();
        
		createContentValues(history, values);
		
		long id = this.getWritableDatabase().insert("location_history", null, values);
		return id;
	}
	
	public List<LocationHistory> getLocationsHistory()
	{
		List<LocationHistory> locationsHistory = new ArrayList<LocationHistory>();
		Cursor  locationsCursor = this.getReadableDatabase().query("location_history",
					new String [] { "time", "location", "precision"},
					null, null, null, null, "time");
		locationsCursor.moveToFirst();
		if ( ! locationsCursor.isAfterLast())
		{
			do
			{
				String time = locationsCursor.getString(0);
				String location = locationsCursor.getString(1);
				String precision = locationsCursor.getString(2);
				

				LocationHistory history = new LocationHistory();
				history.setTime(time);
				history.setPrecision(precision);
				history.setLocation(location);
				
				locationsHistory.add(history);
			}
			while (locationsCursor.moveToNext());
			
		}
		locationsCursor.close();
		return locationsHistory;
	}
	
	@Override
	public void close()
	{
		this.getWritableDatabase().close();
		super.close();
		
	}

}
